var API = require('../../utils/api.js')

wx.cloud.init({ traceUser: true })
var db = wx.cloud.database()

Page({
  data: {
    novelId: '',          // 书架中小说id，用于更新小说章节
    bookName: '',         // 书名 
    title: '',            // 章节标题
    content: '',          // 章节内容
    nowId: 0,              //当前章节索引
    nowContentId: '',      //当前章节id
    prevId: '',          // 上一章节地址
    nextId: '',          // 下一章节地址
    timer:'',

    all: [],        // 所有列表信息
    isShowPage: false,          // 是否显示大分页
    chapterVisible: false,      // 左侧章节抽屉是否可见
    order: 'asc',

    menuVisible: false,         // 菜单抽屉是否可见。'目录' | '设置' | '白天/黑夜'
    isDark: false,              // 白天还是黑夜

    settingVisible: true,      // 设置抽屉是否可见。字体大小、背景颜色、亮度
    
    scrollTop: 0,
    colors: [
      {
        'bg': '#fff',
        'color': '#000'
      },
      {
        'bg': 'rgb(222, 195, 150)',
        'color': '#000'
      },
      {
        'bg': 'rgb(192, 214, 234)',
        'color': '#000'
      },
      {
        'bg': 'rgb(210, 229, 202)',
        'color': '#000'
      },
      {
        'bg': 'rgb(17, 17, 17)',
        'color': 'rgb(70,70,70)'
      },

    ],
    textlLocation:0,
    scrollHeight:0,
    font: 32,
    bgColor: '#fff',
    fontColor: '#000',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (option) {
    let id = option.id;
    this.setData({
      novelId: id
    })
    this.handleInitSettings(id)
    this.handleGetChapterList(id)
  },
  onShow: function(){
    var self= this;
    var timer = setInterval(function () {
      self.updataReadTime();
    }, 60000)
    this.setData({
      timer:timer
    })
  },
  onHide: function(){
    var timer = this.data.timer;
    clearInterval(timer)
  },

  updataReadTime: function(){
    var userId = wx.getStorageSync('id')
    API.updateuserreadtimebyid({
      id:userId
    }).then(resp=>{

    })
  },

  /**
   * wx.navigateBack() 时触发 onUnload 声明周期函数
   * 将用户当前阅读配置存到本地缓存
   */
  onUnload: function () {
    var timer = this.data.timer;
    clearInterval(timer)
    const { bgColor, font, fontColor} = this.data
    wx.setStorageSync('bgColor', bgColor)
    wx.setStorageSync('font', font)
    wx.setStorageSync('fontColor', fontColor)
  },

  getRichHeight:function(){
    var self = this;
    wx.createSelectorQuery().select('#richtxt').boundingClientRect(function(rect){
      self.setData({
        scrollHeight: rect.height
      })
    }).exec()
    
  },

   round: function(v){
    var t=1;
    var e =4;
    for(;e>0;t*=10,e--);
    for(;e<0;t/=10,e++);
    return Math.round(v*t)/t;
  },

  /**
   * 查询章节内容
   */
  handleGetContent: function (id,indexNum) {
      API.getbookcontent({
        id:id,
        indexNum:indexNum
      }).then(resp=>{
        console.log(resp)
        this.setData({
          title:resp.bookIndex.indexName,
          content: resp.content,
          nowId: resp.bookIndex.indexNum,
          scrollTop:0
        })
        this.getRichHeight()
        this.handleUpdataHistory(id,resp.bookIndex.indexNum)
      })
  },
  /* *
   * 初始化用户阅读设置：字体大小、颜色、背景颜色
   */
  handleInitSettings: function (id) {
    const bgColor = wx.getStorageSync('bgColor') || '#fff'
    const font = wx.getStorageSync('font') || 32
    const fontColor = wx.getStorageSync('fontColor') || '#000'
    this.setData({ 
        bgColor:bgColor,
        font:font,
        fontColor:fontColor
    })
    var userId = wx.getStorageSync('id')
    console.log(userId)
    console.log(id)
    API.gethistory({
      bookId:id,
      userId:userId
    }).then(resp=>{
      if(resp){
        this.handleGetContent(id,resp.indexNum)
      }else{
        this.handleGetContent(id,0)
      }
    })
  },

  /**
   * 查询章节列表
   */
  handleGetChapterList: function (id) {
    API.getBookIndex({
      // "id": option.id
      id: id
    }).then(resp => {
      console.log(resp)
      this.setData({
        all: resp,
      })
    })
  },

  /**
   * 翻页。上一页 | 下一页
   */
  handleTurnPage(e) {
    var index= e.currentTarget.dataset.index;
    var info = e.currentTarget.dataset.info;
    var length = this.data.all.length-1;
    var bookId = this.data.novelId;
      if (info === 'prev') {
        if(index === 0){
          wx.showToast({
            title: '已经是第一章了',
            icon: 'none',
          })
        }else{
          this.handleGetContent(bookId,index-1)
        }
      } else{
        if(index===length){
          wx.showToast({
            title: '已经是最新章节了',
            icon: 'none',
          })
        }else{
          this.handleGetContent(bookId,index+1)
        }
      }
  },

  handleUpdataHistory: function(bookId,indexNum){
    var userId = wx.getStorageSync('id')
    API.updatauserreadHistory({
      userId:userId,
      indexNum:indexNum,
      bookId:bookId
    }).then(resp=>{

    })
  },

  /**
   * 修改设置面板中的亮度：白天/黑夜
   */
  handleSwitchTheme: function (e) {
    this.handleHideMenuModal()
    var isDark = e.currentTarget.dataset.theme
    if (isDark) {  // true 表示切换为黑夜
      this.setData({
  
        bgColor: '#fff',
        fontColor: '#000',
        isDark: !isDark
      })
    } else {
      this.setData({

        bgColor: 'rgb(17, 17, 17)',
        fontColor: 'rgb(70,70,70)',
        isDark: !isDark
 
      })
    }
  },
  
  /**
   * 修改设置面板中的字体
   */
  handleChangeFont: function (e) {
    var target = e.currentTarget.dataset.target
    var font = this.data.font
    if (target === 'sub') {
      this.setData({ 
        font: font - 4 
      })
    } else if (target === 'add') {
      this.setData({ 
        font: font + 4 
      })
    } else {
      this.setData({ 
          font: 32 
      })
    }
  },

  /**
   * 修改设置面板中的背景颜色
   */
  handleChangeBg: function (e) {
    var bg = e.currentTarget.dataset.bg
    var fontColor = e.currentTarget.dataset.color
    this.setData({
   
        bgColor: bg,
        fontColor: fontColor
      
    })
  },

  /**
   * 点击章节
   */
  handleClickChapter: function (e) {
    var { id } = e.currentTarget.dataset
    var bookId = this.data.novelId;
    this.handleGetContent(bookId,id)
    this.handleHideMenuModal()
  },



  /**
   * 显示菜单模态框
   */
  handleShowMenuModal: function () {
    this.setData({ menuVisible: true })
  },

  /**
   * 隐藏菜单模态框
   */
  handleHideMenuModal: function () {
    this.setData({
      menuVisible: false,
      chapterVisible: false,
      settingVisible: true,
    })
  },

  /**
   * 显示设置模态框
   */
  handleShowSettingModal: function () {
    this.setData({ settingVisible: false })
  },

  /**
   * 隐藏设置模态框
   */
  handleHideSettingModal: function () {
    this.setData({
      menuVisible: false,
      chapterVisible: false,
      settingVisible: true,
    })
  },

  /**
   * 显示目录模态框
   */
  handleShowChapterModal: function () {
    this.setData({ chapterVisible: true })
  },

  /**
   * 隐藏目录模态框
   */
  handleHideChapterModal: function () {
    this.setData({
      menuVisible: false,
      chapterVisible: false,
      settingVisible: true,
    })
  },
})